package model

import (
	"mlgmd.com/hearsay/base"
	"mlgmd.com/hearsay/entities"
	"mlgmd.com/hearsay/utils"
	"xorm.io/xorm"
)

type Person struct {
	entities.User
	HearsayList []entities.Hearsay `json:"hearsayList"`
	Rewards     []entities.Reward  `json:"rewards"`
	Comments    []PersonComment    `json:"comments"`
}

func (Person) Get(DB xorm.Interface, id int) (data Person, err error) {
	defer base.Error(&err)
	base.Has(base.Must2(DB.ID(id).Get(&data.User)))
	base.Must(DB.Where("blocked = 0 and deleted_time = 0 and creator_id = ?", data.Id).Find(&data.HearsayList))
	base.Must(DB.Where("blocked = 0 and deleted_time = 0 and creator_id = ?", data.Id).Find(&data.Rewards))
	base.Must(PersonComment{}.Query(DB).Where("c.deleted_time =0 and c.target_id = ?", data.Id).Find(&data.Comments))
	// 将回复某个评论的评论与这个评论关联
	cm := utils.MapByKey(data.Comments)
	for i, v := range data.Comments {
		if c, has := cm[v.ReplyToId]; has {
			data.Comments[i].ReplyTo = c.UserComment
		}
	}
	return
}

func (p *Person) Mask() {
	p.User.Mask()
	utils.Foreach(p.HearsayList, base.MaskPtr[*entities.Hearsay])
}

type PersonComment struct {
	entities.UserComment `xorm:"extends"`
	Creator              entities.User        `xorm:"extends" json:"creator"`
	ReplyTo              entities.UserComment `json:"replyTo"`
	Unlocked             bool                 `json:"unlocked"` // 评论的用户是否解锁传闻
	Result               int                  `json:"result"`   // 评论的用户对传闻的评价
}

func (PersonComment) Query(DB xorm.Interface) *xorm.Session {
	return DB.Table([]any{&entities.UserComment{}, "c"}).
		Join("INNER", []any{&entities.User{}, "u"}, "u.id = c.creator_id")
}
